package com.vf.cloud.paas.app.master.common.server.agentManager;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.vf.cloud.paas.app.master.common.server.agentManager.channel.AgentManagerChannelInitializer;
import com.vf.cloud.paas.common.service.IRedis;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class AgentManagerServer {

	@Autowired
	private IRedis redisImpl;

	@Value("${master.dispatch.port}")
	private int renderPort;

	private EventLoopGroup boss;
	private EventLoopGroup work;
	private Channel channel;

	@Async
	public void run() {
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			boss = new NioEventLoopGroup();
			work = new NioEventLoopGroup();

			log.info(">>>正在启动 --> AgentManagerServer:" + renderPort);
			bootstrap.group(boss, work);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(512 * 1024, 1024 * 1024));
			bootstrap.childHandler(new AgentManagerChannelInitializer(redisImpl));
			channel = bootstrap.bind(renderPort).sync().channel();
			log.info(String.format(">>> AgentManagerServer listening on *:%s." ,renderPort));
			
			if(channel!=null  && channel.closeFuture()!=null) {
				channel.closeFuture().sync();
			}
		} catch (Exception e ) {
		} finally {
			work.shutdownGracefully();
			boss.shutdownGracefully();
			log.info(">>>已关闭 --> AgentManagerServer:" + renderPort);
		}
	}

	public void destroy() {
		if(channel!=null) {
			channel.close();
		}
		work.shutdownGracefully();
		boss.shutdownGracefully();
	}

}
